import {
	baseUrl
} from './env'
import {getStore} from '../config/mUtils'
 import eduAlert from '../alert/alert'
export default async(url = '', data = {}, type = 'GET', method = 'fetch') => {
	type = type.toUpperCase();
	url = baseUrl + url;

	if (type == 'GET') {
		let dataStr = ''; //数据拼接字符串
		Object.keys(data).forEach(key => {
			dataStr += key + '=' + data[key] + '&';
		})
		if (dataStr !== '') {
			dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
			url = url + '?' + dataStr;
		}
	}

	if (window.fetch && method == 'fetch') {
    let requestConfig;
	  if(getStore('user_id')){
       requestConfig = {
        credentials: 'include',
        method: type,
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
          'Authorization':'Bearer '+getStore('user_id')
        },
        mode: "cors",
        cache: "reload"
      }
    }else {
       requestConfig = {
        credentials: 'include',
        method: type,
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
        mode: "cors",
        // cache: "force-cache"
         cache: "reload"
      }
    }


		if (type == 'POST') {
			Object.defineProperty(requestConfig, 'body', {
				value: JSON.stringify(data)
			})
		}

		try {
			const response = await fetch(url, requestConfig);
			const responseJson = await response.json();
			if(responseJson.code === 200){
			  return responseJson.data
      }
      if(responseJson.code === 500){
        eduAlert.eduToast(""+responseJson.msg,1000)
        responseJson.error=true;
        return responseJson;
      }
      // this.$layer.toast({
      //   icon: 'icon-check', // 图标clssName 如果为空 toast位置位于下方,否则居中
      //   content: ''+responseJson.msg,
      //   time: 2000 // 自动消失时间 toast类型默认消失时间为2000毫秒
      // })
      // return;
      responseJson.error=true;
      return responseJson;
		} catch (error) {
			throw new Error(error)
		}
	} else {
		return new Promise((resolve, reject) => {
			let requestObj;
			if (window.XMLHttpRequest) {
				requestObj = new XMLHttpRequest();
			} else {
				requestObj = new ActiveXObject;
			}

			let sendData = '';
			if (type == 'POST') {
				sendData = JSON.stringify(data);
			}

			requestObj.open(type, url, true);
			requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			requestObj.send(sendData);

			requestObj.onreadystatechange = () => {
				if (requestObj.readyState == 4) {
					if (requestObj.status == 200) {
						let obj = requestObj.response
						if (typeof obj !== 'object') {
							obj = JSON.parse(obj);
						}
						resolve(obj)
					} else {
						reject(requestObj)
					}
				}
			}
		})
	}
}
